import * as UserApi from '@/api/user'
import authority from '@/utils/authority'

const state = {
  user: authority.get() || {},
}

const mutations = {
  SET_USER: (state, payload) => {
    Object.assign(state, payload)
  },
}

const actions = {
  // 登录
  async login({ commit }, { phone = '', code = '' }) {
    const { user = {}, token } = await UserApi.login({
      phone: phone.trim(),
      code: code,
    })
    user.token = token
    authority.set(user)
    commit('SET_USER', { user })
  },
  // 登出
  async logout({ commit }) {
    await UserApi.logout()
    commit('SET_USER', {
      user: {}
    })
    authority.clear()
    window.location.reload()
  },
}

export default {
  state,
  mutations,
  actions
}